package org.example.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig
{
//    @Bean
//    public UserDetailsService userDetailsService()
//    {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withDefaultPasswordEncoder().username("user").password("321321").roles("USER").build());
//        return manager;
//    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
    {
        // 开启授权保护
        http.authorizeRequests(auhorize -> auhorize
                        // 对所有请求开启授权保护
                        .anyRequest()
                        // 对已认证的请求会被自动授权
                        .authenticated())
                .formLogin(Customizer.withDefaults())  // 使用表单授权方式
//                .httpBasic(Customizer.withDefaults()) // 使用基本授权方式
        ;
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService()
    {
       DBUserDetailsManager manager = new DBUserDetailsManager();
        return manager;
    }
}
